<template>
    <div class="AddUpdata">
        <el-dialog
         ref='dialog'
        :title="dialogtype.adduser?'新增用户':dialogtype.upDatauser?'修改用户':'用户信息'"
        :visible.sync="dialogvisible"
         width="60%"
        :before-close="handleClose">
        <span style="font-size:17px;color:#041f41"><b>基本信息</b></span>
        <div class="form">
             <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="ruleForm">
                 <el-form-item v-for="(item,index ) in ruleFormData" :key="index"  :label="item.label" :prop="item.prop">
                      <label  v-show="dialogtype.detailuser"  class="ruformlabel">{{ruleForm[item.prop]?ruleForm[item.prop]:'无'}}</label>
                     <el-input  v-show="!dialogtype.detailuser" v-if="item.style == 'input'" :type="item.textarea?'textarea':'input'"  v-model="ruleForm[item.prop]"  :placeholder="item.plc" :ref="item.ref"></el-input>
                     <el-select  @change="changeSelect" v-show="!dialogtype.detailuser" v-if="item.style == 'select'" v-model="ruleForm[item.prop]" :placeholder="item.plc">
                        <el-option 
                        clearable
                        v-for="(items,index) in item.children"
                        :key="index"
                       
                        :label="items.label" :value="items.value">
                      
                        </el-option>
                    </el-select>
                        <el-cascader v-show="!dialogtype.detailuser" v-if="item.style == 'region'" v-model="ruleForm[item.prop]" :placeholder="item.plc"
                        :options="citys"
                    >
                    </el-cascader> 
                     <el-radio-group v-show="!dialogtype.detailuser"  v-if="item.style =='radio' " v-model="ruleForm[item.prop]">
                        <el-radio label="启用"></el-radio>
                        <el-radio label="禁用"></el-radio>
                    </el-radio-group>
                  </el-form-item>
            </el-form>
        </div>
        <div class="role">
             <span style="font-size:17px;color:#041f41"><b>{{dialogtype.adduser||dialogtype.upDatauser?'配置权限':'权限信息'}}</b></span>
             <p v-if='!dialogtype.detailuser' class="roleinfo">系统权限</p>
           <el-table v-if="dialogtype.detailuser"
             border
            :span-method="arraySpanMethod"
            show-overflow-tooltip
            :data="detailTable"
           >
            <el-table-column
                v-for="(item,index) in tableHeaderData"
                :key="index"
                :width="item.width"
                :prop="item.prop"
                :label="item.label"
                align="center"
                >
            </el-table-column>
           </el-table> 
             <el-tree
                v-else
                :data="data"
                ref="tree"
                show-checkbox
                 node-key="id"
                @check-change="getCurrentKey"
                :default-expanded-keys="[]"
                :default-checked-keys="checkeys"
                >
                
           </el-tree>


        </div>
        <span slot="footer" class="dialog-footer" v-if="dialogtype.detailuser">
          
            <el-button type="primary" class="feicuilu" @click="handleClose">返回</el-button>
        </span>
         <span slot="footer" class="dialog-footer" v-else>
            <el-button  class='restbtn' @click="resetForm('ruleForm')">重置</el-button>
            <el-button type="primary" class="feicuilu" @click="submitForm('ruleForm')">确定</el-button>
        </span>
      </el-dialog>

    </div>
</template>

<script>
import bus from '../publicJS/bus'
import publicData from '../publicJS/publicData'

    export default {
        props:['dialogVisible','dialogtype'],
        data () {
          var  Rgecellphone =(rules,value,callback) =>{
             let repeate = false
             let firstphone = sessionStorage.getItem('cellphone')
             let reg = /^1(3|4|5|7|8|6|9)\d{9}$/
                if(this.dialogtype.adduser){
                  repeate = true // 开启判断是否已经注册过的
                }
                if(reg.test(value)){
                  console.log("第一次的值",firstphone,"输入的值",value)
                   if(value ==  firstphone){
                     repeate = false
                   }else  {
                     repeate = true 
                   }
                   this.$ajax.post('/index.php/system/hqlrole/registerByCellphone',{cellphone:value,repeate:repeate}).then((res)=>{
                    if(res.data.code == 1 ) {
                      callback()
                    }else{
                      callback(new Error("此号码已经存在，请重新输入号码"))
                    }
                 })
             }else{
               return callback(new Error("请输入正确的手机号码"))
             }
          }
            return {
                dialogvisible: this.dialogVisible,
                city:publicData.city,
                citys:[],
                unitType:[], // 单位类型的数组
                checkeys:[], // 修改用户 默认展开的列表
                checknode:[], // 养护选择的配置权限
                checknodes:[], // 建设选择的配置权限
                ruleForm:{},
                rules:{
                  name:[{required: true, message: '请输入用户姓名', trigger: 'blur'}],
                  cellphone:[{required:true, validator: Rgecellphone, trigger: 'change' }],
                  level:[{required: true, message: '请选择行政级别', trigger: 'change'}],
                  area_code:[{required: true, message: '请选择行政区域', trigger: 'change'}],
                  unit_type:[{required: true, message: '请选择单位类型', trigger: 'change'}],
                  disabled:[{required: true, message: '请勾选账户状态', trigger: 'change'}],
                 
                },
                ruleFormData:[
                    {label:"用户姓名",prop:"name",style:"input",plc:"请输入用户姓名"},
                    {label:"联系手机",prop:"cellphone",style:"input",plc:"请输入用户手机号码"},
                    {label:"职位",prop:"position",style:"input",plc:"请输入职位，最多20字符"},
                    {label:"行政级别",prop:"level",style:"select",opreate:"changselect",plc:"请选择行政级别",children:[{label:"省",value:"省"},{label:"市",value:"市"},{label:"县",value:"县"}]},
                    {label:"行政区域",prop:"area_code",style:"region",plc:"请选择行政区域"},
                    {label:"单位类型",prop:"unit_type",style:"select",plc:"请输选择单位类型",children:[]},
                    {label:"其他",prop:"unit_type1",style:"input",plc:"请输入具体单位类型",ref:"other"},
                    {label:"备注",prop:"remark",style:"input",textarea:true},
                    {label:"状态",prop:"disabled",style:"radio"},
                ],
                tableHeaderData:[
                    {label:"序号",prop:"id",width:"60"},
                    {label:'工程类型',prop:"menu_name",width:"130"},
                    {label:"子模块",prop:"children_menu_name",width:"190"},
                    {label:"权限",prop:"user_type"}
                ],
                data: publicData.data,
                detailTable:[],
                defaultProps: {
                children: 'children',
                label: 'label'
               },
               spanArr:[],
               pos:0

            }
        },
        updated () {
            console.log(this.ruleForm)
           
        },
        methods: {
            handleClose (done){
                this.dialogvisible = false
                this.$emit('closedialog',this.dialogvisible)
            },
            getCurrentKey (key) {
              console.log(key)
             console.log(this.checknode =  this.$refs.tree.getCheckedKeys().filter((item=>{
                return typeof item !='number' && item.includes('-') && item.charAt(0) !='1' && item.charAt(0) !='8'
             }))) 
              console.log(this.checknodes =  this.$refs.tree.getCheckedKeys().filter((item=>{
                return typeof item !='number' && item.includes('-') && (item.charAt(0) =='1' || item.charAt(0)=='8')
                
             }))) 

            },
            submitForm(formName) {
              this.$refs[formName].validate((valid) => {
              if (valid) {
                  console.log("验证通过")
                  if(this.dialogtype.upDatauser){
                    this.updateduser()
                  }else {
                    this.AddUser()
                  }
                 
               //   this.$emit('closedialog',this.dialogvisible)  
              }else {
                console.log('error submit!!');
                 if(this.checknode.length == 0 && this.checknodes.length ==0){
                   this.messages(0,'请为用户至少添加一个系统权限')

                 }else {
                   this.$nextTick(()=>{
                       this.messages(0,'请完成所有必填项').catch(()=>{
                           console.log(this.$refs.dialog.$el.scrollTop=0+'px','距离') 
                       })
                   })
                  
                 }
                 
                return false;
            }
          });
        },
            resetForm(formName) {
            this.$refs[formName].resetFields();
            this.$nextTick(() => {
            this.$refs[formName].clearValidate();
           })
            // console.log(this.$refs[formName].resetFields)
            },
            updateduser() {
              let parms  = this.ruleForm
                 console.log (typeof this.ruleForm.area_code)
                  parms.area_code = typeof this.ruleForm.area_code =='string'?this.ruleForm.area_code:this.ruleForm.area_code[this.ruleForm.area_code.length-1]
                  console.log(parms.area_code)
                  parms.id = this.ruleForm.id
                  parms.role={
                    maintain:this.checknode,// 养护类的权限代码
                    build:this.checknodes // 建设类的权限代码

                  }
                  this.$ajax.post("/index.php/system/hqlrole/addUser",parms).then((res)=>{
                    console.log(res)
                    this.messages(res.data.code,res.data.msg).then(()=>{
                      console.log("成功")
                      this.handleClose()
                       this.$emit('repeate') // 重新请求数据

                    }).catch(()=>{
                      console.log("失败")
                    })
                  })

            },
            AddUser() {
               let parms  = this.ruleForm
                   parms.area_code = typeof this.ruleForm.area_code =='string'?this.ruleForm.area_code:this.ruleForm.area_code[this.ruleForm.area_code.length-1]
                  parms.role={
                    maintain:this.checknode,
                    build:this.checknodes
                  }
                  this.$ajax.post("/index.php/system/hqlrole/addUser",parms).then((res)=>{
                    console.log(res)
                    this.messages(res.data.code,res.data.msg).then(()=>{
                      console.log("成功")
                      this.handleClose()
                       this.$emit('repeate') // 重新请求数据

                    }).catch(()=>{
                      console.log("失败")
                    })
                  })
            },
           
            changeSelect (value,flag=true) {
                console.log(value)
                 this.citys = JSON.parse(JSON.stringify(this.city));
                  if(this.ruleForm.level!="省" || this.ruleForm.unit_type!="交通厅"){ 
                    this.data[0].disabled =true // data 是 树形结构的数据  只有在省级和交通厅 时 用户管理权限才可选
                    this.data[0].children.forEach((el)=>{
                      el.disabled = true
                      el.children[0].disabled = true
                    })
                  }else {
                    this.data[0].disabled =false
                     this.data[0].children.forEach((el)=>{
                      el.disabled = false
                      el.children[0].disabled = false
                    })
                  }
                  if(value =="市" && flag){  
                   this.ruleForm.unit_type = ''         
                   //this.ruleFormData[5].children[0].disabled = true  // 市和县区 禁用 交通厅
                   /* if(this.ruleFormData[5].children[0].label=="交通厅"){
                       this.$nextTick(()=>{               
                          //  this.ruleFormData[5].children=[]
                            this.ruleFormData[5].children=[{label:"公路局",value:"公路局"},{label:"交通局",value:"交通局"},{label:"其他",value:"其他"}]
                        })
                    }*/
                   this.ruleFormData[5].children= this.ruleFormData[5].children.filter(el=>{
                      return el.value!='交通厅'
                    })
                    if(!this.ruleFormData[5].children.find(el=>{ return el.value == '交通局'})){
                      this.ruleFormData[5].children.unshift({label:"交通局",value:"交通局"})
                    }
                    console.log('市',this.ruleFormData[5].children)

                    this.citys = this.citys[0].children.filter(res=>{ 
                      return delete res.children
                    })
                }else if  (value == "县"  && flag) {
                    this.ruleForm.unit_type = ''     
                 /* if( this.ruleFormData[5].children[0].label=="交通厅"){
                        this.$nextTick(()=>{
                           // this.ruleFormData[5].children=[]
                             this.ruleFormData[5].children=[{label:"公路局",value:"公路局"},{label:"交通局",value:"交通局"},{label:"其他",value:"其他"}]
                        })
                    }*/
                      this.ruleFormData[5].children= this.ruleFormData[5].children.filter(el=>{
                      return el.value!='交通厅'
                    })
                     if(!this.ruleFormData[5].children.find(el=>{ return el.value == '交通局'})){
                      this.ruleFormData[5].children.unshift({label:"交通局",value:"交通局"})
                    }
                 console.log('县',this.ruleFormData[5].children)
                    this.citys = this.city[0].children
                }else if(value== "省"  && flag) { // 省级没有交通局
                   this.ruleForm.unit_type = ''  
                 /*  if( this.ruleFormData[5].children[0].label!="交通厅"){
                        this.$nextTick(()=>{
                        //  this.ruleFormData[5].children=[]
                          this.ruleFormData[5].children=[{label:"交通厅",value:"交通厅"},{label:"公路局",value:"公路局"},{label:"水运局",value:"水运局"},{label:"财政厅",value:"财政厅"},{label:"其他",value:"其他"}]
                        })
                      
                    }else {
                      this.ruleFormData[5].children.splice(1,1) // 页面第一进入的时候 第一个值是交通厅
                    }*/
                
                    if(!this.ruleFormData[5].children.find(el=>{ return el.value == '交通厅'})){
                      this.ruleFormData[5].children.unshift({label:"交通厅",value:"交通厅"})
                    }
                     this.ruleFormData[5].children= this.ruleFormData[5].children.filter(el=>{
                       return el.value != '交通局'

                     })
                     this.citys=[{  id:1, "value": '430000', label: '湖南省',}]
                }else { // 针对于下拉框选择 到 单位类型时 对基本的处理
                   if(this.ruleForm.level == "市") {
                       this.citys = this.citys[0].children.filter(res=>{           
                      return delete res.children
                    })
                    /*  this.ruleFormData[5].children= this.ruleFormData[5].children.filter(el=>{
                      return el.value!='交通厅'
                    })*/
                    //this.ruleFormData[5].children=[{label:"公路局",value:"公路局"},{label:"交通局",value:"交通局"},{label:"其他",value:"其他"}]

                   }else if (this.ruleForm.level == "县"){
                      this.citys = this.city[0].children
                        //this.ruleFormData[5].children=[{label:"公路局",value:"公路局"},{label:"交通局",value:"交通局"},{label:"其他",value:"其他"}] 
                    /*  this.ruleFormData[5].children= this.ruleFormData[5].children.filter(el=>{
                      return el.value!='交通厅'
                    })*/
 
                   }else if (this.ruleForm.level == "省"){
                      this.citys=[{  id:1, "value": '430000', label: '湖南省',}]
                     // this.ruleFormData[5].children=[]
                    //  this.ruleFormData[5].children=[{label:"交通厅",value:"交通厅"},{label:"公路局",value:"公路局"},{label:"水运局",value:"水运局"},{label:"财政厅",value:"财政厅"},{label:"其他",value:"其他"}] 
                  /*  if(!this.ruleFormData[5].children.find(el=>{ el.value == '交通厅'})){
                      this.ruleFormData[5].children.unshift({label:"交通厅",value:"交通厅"})
                    }*/
                   }
                }

                if(value !="其他" && this.ruleForm.unit_type != "其他" ){
                  console.log(this.$refs.other[0].$parent.$el.style.display="none" )
                 this.$set(this.rules,'unit_type1',[])
                }else if(this.ruleForm.unit_type == "其他") {
                   console.log(this.$refs.other[0].$parent.$el.style.display="block" )
                  this.$nextTick(()=>{
                    this.$set(this.rules,'unit_type1',[{required: true, message: '请输入具体单位类型', trigger: 'blur'}])
                  })
                

                }
                  console.log(this.rules)
            }, 
            // 用户详情 信息  提取对应的 权限信息 和需要动态合并的行数
         getDetailUser(){
          this.$ajax.post('/index.php/system/hqlrole/detailsUser',{
            id:this.ruleForm.id,
            listBack:1
          }).then((res)=>{
            console.log(res)
              let id= 0
              let spr = 0
              this._arr = []
              res.data.msg.role.forEach((item,index)=>{
               let menu_name = item.menu_name
               item.children.forEach((items,indexs)=>{
                 let childmenu = items.children_menu_name
                 if(items.children[0].user_type){
                   let obj = {}
                   id++
                   obj.menu_name = menu_name
                   obj.children_menu_name = childmenu
                   obj.user_type = items.children[0].user_type
                   obj.id = id                  
                   this.detailTable.push(obj)
                 }else{
                 }
               })
               
            })
            

           this.dealwith() // 动态合并行数的处理方法
          })
         },
         dealwith () {
           let spr = 1
           for(let i=0 ;i<this.detailTable.length;i++){
               if(i == 0){
                 this.detailTable[i].spr =1
               }else {
                 if(this.detailTable[i].menu_name == this.detailTable[i-1].menu_name){
                    this.detailTable[i].spr = spr
                 }else{
                   spr++
                   this.detailTable[i].spr = spr
                 }
               }

            
           }
            console.log(this.detailTable) // 将相同菜单的spr 设置为一样的
           for (let i = 0; i < this.detailTable.length; i++) {
            if (i === 0) {
              this.spanArr.push(1);
              this.pos = 0
            } else {
              // 判断当前元素与上一个元素是否相同
            if (this.detailTable[i].spr ===this.detailTable[i - 1].spr) {
                this.spanArr[this.pos] += 1;
                this.spanArr.push(0);
              } else {
                this.spanArr.push(1);
                this.pos = i;
              }
            }
         }
         console.log(this.spanArr)

         },
         // 修改用户调用接口 将返回的权限信息保存在checks 里
         getUpDatauser () {   
           this.$ajax.post('/index.php/system/hqlrole/roleSearch',{
            id:this.ruleForm.id,
          }).then((res)=>{
            this.checkeys=[];
             for(let key in res.data.msg.role){
                 res.data.msg.role[key].forEach((item,index)=>{
                   item.forEach((items,index)=>{
                       this.checkeys.push(items.project_type) 
                   })
                })
             }

                // this.$set(this.checkeys,index,item.project_type) 
          })
         },
         getUntiType () { // 获取单位类型
         this.$ajax.post('/index.php/system/hqlrole/unitType').then((res)=>{
           let unitype = res.data
           unitype.data.forEach((item,index)=>{
             let obj = {}
             obj.value = item.unit_type
             obj.label = item.unit_type
             this.unitType.push(obj)
           })
           this.unitType.push({label:'其他',value:'其他'})
           this.$set(this.ruleFormData[5],'children',this.unitType)
           
         }).catch(error=>{
           this.messages(0,'获取单位类型异常，请联系管理员').catch()
         })

         }, 
         arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
           //合并方法 {row 大于0为合并的行数 0 为不显示   [2,1] [0,1],[0,1] 这样返回 为 合并两行}
           if(columnIndex == 1 ){
              const _row = this.spanArr[rowIndex];
              const _col = _row > 0 ? 1 : 0;
            return {
                  rowspan: _row,
                  colspan: 1
            }
            
           } 

         },
        
        messages(code,text) {
          return new  Promise ((resolve,reject)=>{
             if(code == 1) {
              this.$confirm(text,'提示',{
              confirmButtonText: '确定',
              type: 'success'
            });
            resolve()
          }else {
            this.$confirm(text,'提示',{
              confirmButtonText: '确定',
              type: 'error'
            }).then(()=>{
               reject()
            })
          }
        }) 
       },
      },
      
        mounted () {
          this.$nextTick (()=>{
              console.log(this.$refs.other[0].$parent.$el.style.display="none" )// 其他为隐藏
              if(this.dialogtype.upDatauser || this.dialogtype.adduser){
                 this.changeSelect(this.ruleForm.level,false)
              }
             
          })
          sessionStorage.setItem('cellphone',this.ruleForm.cellphone) // 保存用户第一次额值
          this.getUntiType () // 获取单位类型
        },
        
        created () {
          console.log(this.$store.state.ruleform)
          this.ruleForm =  JSON.parse(JSON.stringify( this.$store.state.ruleform)) 
           console.log(this.dialogtype)
           this.citys =JSON.parse(JSON.stringify(this.city));
            if(this.dialogtype.detailuser) { // 详情  或者详情要去请求权限信息
             this.ruleForm.area_code = this.ruleForm.area_name  // 详情里的单位类型area-code
             this.rules = {}
            this.getDetailUser() // 展示详情
           }else if( this.dialogtype.upDatauser) {
              this.ruleForm.area_code = this.ruleForm.area_code         
              this.getUpDatauser() //修改用户
          }

        },
    }
</script>

<style lang="stylus" scoped>
.AddUpdata>>>
 .el-dialog__body
  padding 20px 20px
 .el-dialog__header
   background rgb(4,31,65)
   .el-dialog__title
    color white
   .el-dialog__headerbtn
    color gray
    .el-dialog__close:hover
      color white
.ruleForm
  display flex
  margin-top 30px
  flex-wrap wrap
  justify-content flex-start
  margin-left 58px
  .el-form-item
    flex 0 0 80%
  .el-select
    display block
  .el-cascader
    display block
.ruleForm>>>
  .is-disabled 
   .el-input__inner
     color: #364b74
.form
  border-bottom: 1px solid #ccc;
.role
 margin-top 20px
.role>>>
 .el-tree-node.is-expanded
  .el-tree-node__children
   .el-tree-node
    .el-tree-node__children
     display flex

.role
 .Table >>>
 .el-table 
  th
   background-color rgb(235,245,255) !important
   padding 8px 0

.ruformlabel
 margin-left 10%
.el-table
 margin-top:20px
.role >>>
 .el-table 
  th
   background-color #EBF0FF !important

.role >>> .el-tree 
 margin 40px 103px

.roleinfo
 position absolute
 left 15%
.roleinfo:before
 content:"*"
 color:red
 vertical-align: initial;
 padding-right 3px

.ruleForm>>>
 .el-form-item
   .el-input__inner:focus
    border-color #24B3B3
    outline 0


</style>